import { getLastPage } from '@/utils'
import pagesConfig from '@/pages.json'

// 页面跳转兼容跳转tabbar
// 窗口动画 https://uniapp.dcloud.net.cn/api/router.html#animation
const navigation = {
  navigateTo: uni.navigateTo,
  redirectTo: uni.redirectTo,
  switchTab: uni.switchTab,
  reLaunch: uni.reLaunch,
}

type NavigateType = keyof typeof navigation

type AnimationType = UniNamespace.NavigateToOptions['animationType']
type NavigateParams = Omit<Parameters<Uni[NavigateType]>[0], 'url'> & {
  animationType?: AnimationType
}
type BackAnimationType =
  | 'auto'
  | 'none'
  | 'pop-out'
  | 'slide-out-right'
  | 'slide-out-left'
  | 'slide-out-top'
  | 'slide-out-bottom'
  | 'fade-out'
  | 'zoom-in'
  | 'zoom-fade-in'

// 检测链接是否是tababr页面
export function hasTabbar(path?: string) {
  const { tabBar } = pagesConfig
  const list = tabBar && tabBar.hasOwnProperty('list') ? tabBar.list : []
  if (!list.length) return false
  const url = path ? path.substring(1) : getLastPage().route
  return !!list.find((item) => item.pagePath.includes(url))
}

export function push(_page: string, type: NavigateType = 'navigateTo', options?: NavigateParams) {
  _page = _page.startsWith('/pages') ? _page : '/pages/' + _page
  navigation[type]({
    url: _page,
    ...options,
  })
}

export function to(_page: string, animationType: AnimationType = 'pop-in') {
  if (hasTabbar(_page)) {
    push(_page, 'switchTab')
  } else {
    push(_page, 'navigateTo', {
      animationType,
      fail: (err) => {
        console.log(err, '跳转失败', _page)
      },
    })
  }
}

export function toLogin(isClose = false) {
  const path = 'pages-sub/public/login'
  isClose ? toRedi(path) : to(path)
}

// 关闭当前页跳转
export const toRedi = (_page: string) => push(_page, 'redirectTo')

// 关闭所有页面跳转
export const toRela = (_page: string) => push(_page, 'reLaunch')

// tabbar跳转
export const toTab = (_page: string) => push(_page, 'switchTab')

// 页面返回
export function toBack(delta = 1, animationType: BackAnimationType = 'pop-out') {
  uni.navigateBack({
    delta,
    // #ifdef APP-PLUS
    animationType,
    // #endif
  })
}
